using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Vin.Extension.Framework.Signals.Options;
using Vin.Extension.Framework.Signals.ServiceInterface;
using Vin.Tool.AspNetCore.Singleton;
using Vin.Tool.Core.AssertCategory;

namespace Vin.Extension.Framework.Signals;

public static class SignalsEndpoint
{
    /// <summary>
    /// 扩展信号路由
    /// </summary>
    /// <param name="app"></param>
    /// <param name="routes"></param>
    public static void UseSignalsRoute(WebApplication app, List<SignalsRouteOption> routes)
    {
        foreach (var item in routes)
        {
            if (item.ServiceKey.IsNullOrWhiteSpace() || item.Route.IsNullOrWhiteSpace() ||
                item.Method.IsNullOrWhiteSpace()) continue;
            app.MapMethods(item.Route!, new[] { item.Method! }, async () =>
            {
                var service = VinApp.GetRequiredKeyServiceByHttpContext<IVinSignalService>(item.ServiceKey);
                return TypedResults.Ok(Activator.CreateInstance(VinApp.ApiResultType, 200, "请求成功",
                    await service.SendSignalAsync(TimeSpan.FromSeconds(item.ExpireSecond), item.Prefix!), 0));
            });
        }
    }
}